package com.singfan.common.util;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * Author: hansonghe
 * Date: 2015-08-21 11:57
 * Desc:
 */
public class HttpClientUtil {
    private static final int TIMEOUT = 10000;

    /**
     * 发送post请求
     * @param url 请求的地址
     * @param data 请求的数据
     * @param isHttps 是否https协议
     * @return 响应结果
     * @throws Exception
     */
    public static String post(String url, String data, boolean isHttps) throws Exception {
        HttpContext httpContext = new BasicHttpContext();
        HttpPost post = new HttpPost(url);
        HttpParams requestParams = new BasicHttpParams();
        //设个超时时间，别让服务器的问题堵住
        requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);//ms
        requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
        post.setParams(requestParams);
        DefaultHttpClient client = getClient(isHttps);
        try {
            StringEntity stringEntity = new StringEntity(data);
            post.setEntity(stringEntity);
            HttpResponse response = client.execute(post, httpContext);
            return EntityUtils.toString(response.getEntity());
        }
        catch (Exception e) {
            post.abort();
            throw e;
        }
        finally {
            client.getConnectionManager().shutdown();
        }
    }

    /**
     * 发送get请求
     * @param url 请求的地址
     * @param isHttps 是否https协议
     * @return 响应结果
     * @throws Exception
     */
    public static String get(String url, boolean isHttps) throws Exception{
        HttpContext httpContext = new BasicHttpContext();
        HttpGet get = new HttpGet(url);
        HttpParams requestParams = new BasicHttpParams();
        //设个超时时间，别让服务器的问题堵住
        requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);//ms
        requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
        get.setParams(requestParams);
        DefaultHttpClient client = getClient(isHttps);
        try {
            HttpResponse response = client.execute(get, httpContext);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            get.abort();
            throw e;
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    private static DefaultHttpClient getClient(boolean isHttps) throws NoSuchAlgorithmException, KeyManagementException {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        if (isHttps) {
            defaultHttpClient = new DefaultHttpClient();
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
            defaultHttpClient  = new DefaultHttpClient(ccm, defaultHttpClient.getParams());
        }

        return defaultHttpClient;
    }
}
